/*
 * Author: Jpeng
 * Email: peng8350@gmail.com
 * Time:  2019-08-31 10:58
 */

// convert footer to header to use ,behaviour almost same with header

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class FooterUnderScroll extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ConvertFooterState();
  }
}

class _ConvertFooterState extends State<FooterUnderScroll> {
  RefreshController _refreshController = RefreshController();

  List<String> data = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
  int nextIndex = 1;
  int preIndex = 1000;

  Widget buildCtn() {
    return ListView.separated(
      physics: ClampingScrollPhysics(),
      padding: EdgeInsets.only(left: 5, right: 5),
      itemBuilder: (c, i) => Item(
        title: data[i],
      ),
      separatorBuilder: (context, index) {
        return Container(
          height: 0.5,
          color: Colors.greenAccent,
        );
      },
      itemCount: data.length,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SmartRefresher(
          enablePullUp: true,
          enablePullDown: true,
          footer: ClassicFooter(loadStyle: LoadStyle.ShowWhenLoading,),
          child: buildCtn(),
          onRefresh: () async {
            await Future.delayed(Duration(milliseconds: 1000));

            for (int i = 0; i < 20; i++) {
              var t = preIndex--;
              data.insert(0, t.toString());
            }

            setState(() {});
            _refreshController.refreshCompleted();
          },
          onLoading: () async {
            await Future.delayed(Duration(milliseconds: 1000));

            for (int i = 0; i < 5; i++) {
              var t = nextIndex++;
              data.add(t.toString());
            }

            setState(() {});
            _refreshController.loadFailed();
            // _refreshController.loadFailed();
          },
          controller: _refreshController,
        ),
      appBar: AppBar(),
    );
  }
}


class Item extends StatefulWidget {
  final String title;

  Item({required this.title});

  @override
  _ItemState createState() => _ItemState();
}

class _ItemState extends State<Item> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Card(
        margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
        child: Center(
          child: Text(widget.title),
        ),
      ),
      height: 100.0,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}